<?php

namespace Modules\Admin\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
use Modules\Admin\Entities\Admin;

class AdminRequest extends FormRequest {
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules() {
        switch ($this->method()) {
            case "POST":
                return [
                    'username' => 'required|string|between:4,16|unique:' . Admin::getTableName() . ',username,NULL,id,deleted_at,NULL',
                    'name' => 'required|string|between:2,10',
                    'password' => ['required', 'string', 'between:6,16',
                        Password::min(6)
                            ->letters()//使密码至少需要一个字母。
                            ->numbers()//使密码至少需要一个数字。
                            ->mixedCase()//使密码至少需要一个大写和一个小写字母。
                            ->symbols()//使密码至少需要一个符号。
                            ->uncompromised()//确保密码没有在数据泄露中被泄露。
                    ],
                    'enable_status' => 'boolean',
                    'mobile' => ['required', 'phone:CN', Rule::unique(Admin::getTableName())->whereNull('deleted_at')],
                ];
            case "PUT":
            case "PATCH":
                $admin = $this->route('admin');
                return [
                    'username' => 'string|between:4,16|unique:' . Admin::getTableName() . ',username,' . $admin->id . ',id,deleted_at,NULL',
                    'name' => 'string|between:2,10',
                    'password' => ['string', 'between:6,16',
                        Password::min(6)
                            ->letters()//使密码至少需要一个字母。
                            ->numbers()//使密码至少需要一个数字。
                            ->mixedCase()//使密码至少需要一个大写和一个小写字母。
                            ->symbols()//使密码至少需要一个符号。
                            ->uncompromised()//确保密码没有在数据泄露中被泄露。
                    ],
                    'enable_status' => 'boolean',
                    'mobile' => [
                        'phone:CN',
                        Rule::unique(Admin::getTableName(), 'mobile')
                            ->where(function ($query) use ($admin) {
                                return $query->where('id', '<>', $admin->id);
                            })
                            ->whereNull('deleted_at'),
                    ],
                ];

        }
        return [
            //
        ];
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize() {
        return true;
    }

}
